package net.sourceforge.cobertura.instrument;

import java.io.InputStream;
import java.util.Collection;
import java.util.Vector;

import net.sourceforge.cobertura.coveragedata.ClassData;
import net.sourceforge.cobertura.coveragedata.ProjectData;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;

public class PublicClassInstrumenter {
  
  public InstrumentedClass instrument(Class clazz) throws Exception {
    String name = clazz.getName().replaceAll("\\.", "/") + ".class";
    InputStream is = clazz.getClassLoader().getResourceAsStream(name);
    //System.out.println("Uninstrumented: " + is.available());
    ClassReader cr = new ClassReader(is);
    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    ProjectData projectData = new ProjectData(); // return this?
    Collection ignoreRegexes = new Vector();
    Collection ignoreBranchesRegexes = new Vector();
    ClassInstrumenter cv = new ClassInstrumenter(projectData, cw, ignoreRegexes, ignoreBranchesRegexes);
    cr.accept(cv, 0);
    //System.out.println(" Instrumented?: " + cv.isInstrumented());
    //System.out.println("  # of classes: " + projectData.getNumberOfClasses());
    ClassData classData = projectData.getClassData(clazz.getName());
    //System.out.println(" Instrumented?: " + classData.containsInstrumentationInfo());
    //System.out.println("   Valid Lines: " + classData.getNumberOfValidLines());
    //System.out.println(" Line Coverage: " + classData.getLineCoverageRate());

    byte[] instrumentedClass = cw.toByteArray();
    //System.out.println("  Instrumented: " + instrumentedClass.length); 
    
    return new InstrumentedClass(cw.toByteArray(), classData, projectData);
  }

}
